package com.framework.common.utils;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class SnowflakeIdWorker {
    private static long workerId;
    private static long datacenterId;

    @Value("${snowflake.workerid:1}")
    int _workerId;
    @Value("${snowflake.datacenterid:1}")
    int _datacenterId;

    @PostConstruct
    public void beforeInit() {
        this.datacenterId = _datacenterId;
        this.workerId = _workerId;
    }

    private static Snowflake snowflake;

    public static Snowflake getSnowflake() {
        if (snowflake == null) {
            //参数1为终端ID 参数2为数据中心ID
            snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        }
        return snowflake;
    }


    /**
     * 获取id
     */
    public static Long nextId() {
        long id = getSnowflake().nextId();
        return id;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(nextId());
        }
    }

}
